package net.dl.ss.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.dl.ss.dao.CategAdjudicatorDao;
import net.dl.ss.domain.CategAdjudicator;
import net.dl.ss.service.ContextManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author yakovlev.yuriy@gmail.com
 * @since 12.8.2008
 */
@Controller
public class CategAdjudicatorsController extends BaseController {
	protected final Log logger = LogFactory.getLog(getClass());
	private final CategAdjudicatorDao categAdjudicatorDao;
	
	@Autowired
	public CategAdjudicatorsController(CategAdjudicatorDao categAdjudicatorDao) {
		this.categAdjudicatorDao = categAdjudicatorDao;
	}
	
	@RequestMapping("/addCategAdjudicator.htm")
	public void addCategAdjudicatorHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream  os = response.getOutputStream();
		modifyResponseHeader(response, "text/plain");

		Long categoryId = ContextManager.getCurrentCategory(request);
	    if(categoryId!=null) {
	    	Long id = getParameter(request,"id",Long.class);
	    	try {
				CategAdjudicator ca = new CategAdjudicator();
				ca.setAdjudicatorId(id);
				ca.setCategoryId(categoryId);
	    		this.categAdjudicatorDao.saveEntity(ca);
				os.print("{success:true}");
			} catch(Exception ex) {
				logger.error(ex.getMessage());
			}
	    } else {
	    	os.print("{success:false}");
	    }
	    os.close();
	}
	
	@RequestMapping("/remCategAdjudicator.htm")
	public void remCategAdjudicatorHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream  os = response.getOutputStream();
		modifyResponseHeader(response, "text/plain");
		try {
			String id = request.getParameter("id");
			if(id!=null && !"".equals(id)) {
				this.categAdjudicatorDao.deleteByCategAndAdjudicator(ContextManager.getCurrentCategory(request), Long.parseLong(id));
				os.print("{success:true}");
			} else {
				os.print("{success:false}");
			}
		} catch(Exception ex) {
			logger.error(ex.getMessage());
		}
	    os.close();
	}
	
}
